package org.iartisan.thought.web.filter;


import org.iartisan.runtime.env.EnvContextConfig;
import org.iartisan.thought.web.integration.query.BasicQueryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

@Configuration
@Order
public class WebConfig extends WebMvcConfigurerAdapter implements ServletContextInitializer {

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {

        return (container -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
            ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500");
            container.addErrorPages(error404Page, error500Page);
        });

    }

    @Autowired
    private BasicQueryClient basicQueryClient;

    protected final static String _categories = "_categories";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setAttribute("_baidutongji", EnvContextConfig.get("baidu.tongji.script"));
        servletContext.setAttribute("_title", EnvContextConfig.get("thought.title", "iartisan-thought"));
        servletContext.setAttribute("_keywords", EnvContextConfig.get("thought.keywords", "Thought,iartisan,开发者社区"));
        servletContext.setAttribute("_description", EnvContextConfig.get("thought.description", "iartisan-thought致力于为web开发提供强劲动力"));
        servletContext.setAttribute("_footer", EnvContextConfig.get("thought.footer", "2018 &copy; <a href=\"https://gitee.com/iartisan/iartisan-thought\" target=\"_blank\" style=\"color: #1E9FFF\">powerd by iartisan-thought</a>"));
        servletContext.setAttribute("_friendLink", EnvContextConfig.get("thought.friendLink", "iartisan-thought致力于为web开发提供强劲动力"));
        servletContext.setAttribute(_categories, basicQueryClient.getCategories());
    }

    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/comment/management/**","/comment/management/**/**");
    }
}
